import apiConfig from './apiConfig'
import Taro from '@tarojs/taro';

//网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams
  const { method, data, url } = requestParams
  let token = Taro.getStorageSync('access_token')//拿到本地缓存中存的token
  requestParams.header = {
    ...requestParams.header,
    token: token //将token添加到头部
  }
  return chain.proceed(requestParams).then(res => { return res })
}

Taro.addInterceptor(interceptor)

const request = async (method, url, params) => {
  //由于post请求时习惯性query参数使用params，body参数使用data，而taro只有data参数，使用contentType作为区分，因此此处需要做一个判断
  let contentType = params?.data ? 'application/json' : 'application/x-www-form-urlencoded';
  if (params) contentType = params?.headers?.contentType || contentType;
  const option = {
    method,
    isShowLoading: false,
    url: apiConfig.baseUrl + url,
    data: params && (params?.data || params?.params),
    header: {
      'content-type': contentType,
    },
    success(res) {
        if(res.statusCode==401){
          Taro.removeStorageSync("access_token");
          Taro.reLaunch({
            url: "/pages/login/login",
          });
        }else if(res.statusCode!=200){
          Taro.showToast({
              title: "请求失败",
              icon: "error",
              duration: 2000,
          });
        }
        Taro.hideLoading();
    },
    error(e) {
      console.log('api', '请求接口出现问题', e);
      Taro.showToast({
        title: "请求失败",
        icon: "error",
        duration: 2000,
      });
      Taro.hideLoading();
    }
  }

  Taro.showLoading({ title: "加载中..." });
  const resp = await Taro.request(option);
  return resp;
}


const pullDevices={};

let addPullTime=new Date().getTime();

const addPullDevice=function(page,deviceId){
  let devices= pullDevices[page]; 
  if(!devices){
    devices=[{deviceId:deviceId,time:new Date().getTime()}];
  }else{
    const idx=devices.findIndex(d=>d.deviceId==deviceId);
    if(idx>=0){
      devices.splice(idx,1);
    }
    devices.push({deviceId:deviceId,time:new Date().getTime()});
  }
  pullDevices[page]=devices;
}

const isPullDeviceExist=function(page,deviceId){
  let deviceIds= Taro.getStorageSync('pullTask_'+page);
  return deviceIds && deviceIds.findIndex(d=>d==deviceId)>=0;
}

const removePullDevice=function(page,deviceId){
  if(!deviceId){
    delete pullDevices[page];
  }else{
   let devices= pullDevices[page];
   const idx=devices.findIndex(d=>d.deviceId==deviceId);
   if(idx>=0){
    devices.splice(idx,1);
   }
  }
}

const pullDeviceInfo=async (page,device,time)=>{
  const deviceId=device.deviceId;
  const devices= pullDevices[page];
  if(!devices){
    return ;
  }
  const idx=devices.findIndex(d=>d.deviceId==deviceId);
  if(idx==-1){
    return;
  }
  const addTime=devices[idx].time;

  if(time && time<addTime){
    return;
  }

  //登录时生成唯一客户端ID
  let clientId=Taro.getStorageSync('client_id');

  const lastTime=new Date().getTime();
  const task= Taro.request({
    url:apiConfig.baseUrl +"/device/"+deviceId+"/consumer/"+clientId+"_"+page,
    success(res){
      if(res.statusCode==200){
        let msg = res.data;
        if(msg.type=="property"){
          console.log("set property,from",device.property,"to",msg.data);
          //属性更新
          for(let p in msg.data){
            if(device.property){
              device.property[p]=msg.data[p];
            }
          }
        }else if(msg.type=="state"){
          device.online=msg.identifier=="online";
        }
        //继续拉取
        pullDeviceInfo(page,device,lastTime);
      }
    }
  })
}

export default {
  get: (url, config) => {
    return request('GET', url, config);
  },
  post: (url, config) => {
    return request('POST', url, config);
  },
  put: (url, config) => {
    return request('PUT', url, config);
  },
  delete: (url, config) => {
    return request('DELETE', url, config);
  },
  pullDeviceInfo: (page,device)=>{
    pullDeviceInfo(page,device);
  },
  addPullDevice:(page,deviceId)=>{
    addPullDevice(page,deviceId);
  },
  removePullDevice:(page,deviceId)=>{
    removePullDevice(page,deviceId);
  }
}